import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import { Spin, Form, Button, Radio, Input, message } from 'antd';
import DebounceWrapper from '@/components/DebounceWrapper';
import DraggableModal from '@/components/DraggableModal';
import {
  addDict,
  modifyDict,
  checkDictType,
  fetchAvailableDictChildList,
} from '@/services/system/dictionary';

const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 17 },
};
const { Group } = Radio;
const DebounceButton = DebounceWrapper(Button);

export default ({ visible, options, closeModal, updateList }) => {
  const { id, dictName } = options;
  const [form] = Form.useForm();
  const [initialLoading, setInitialLoading] = useState(true);
  const [statusDict, setStatusDict] = useState([]);
  const [actionLoading, setActionLoading] = useState(false);

  const handleCancel = () => {
    if (!actionLoading) {
      closeModal();
    }
  };
  const handleConfirm = () => {
    setActionLoading(true);
    form
      .validateFields()
      .then((values) => {
        const params = _.assign(id ? { id } : {}, values);
        const confirmAction = params.id ? modifyDict : addDict;
        confirmAction(params)
          .then(() => {
            closeModal();
            setActionLoading(false);
            updateList && updateList();
            message.success(`字典${params.id ? '修改' : '新增'}成功`);
          })
          .catch(() => {
            setActionLoading(false);
          });
      })
      .catch(() => {
        setActionLoading(false);
      });
  };

  const formList = [
    {
      name: 'dictName',
      label: '字典名称',
      initialValue: '',
      rules: [{ required: true, whitespace: true, message: '请输入字典名称' }],
      component: Input,
      componentProps: {
        maxLength: 24,
        allowClear: true,
        placeholder: '请输入字典名称',
        autoComplete: 'off',
      },
    },
    {
      name: 'dictType',
      label: '字典类型',
      initialValue: '',
      validateTrigger: ['onChange', 'onBlur'],
      rules: [
        { required: true, whitespace: true, message: '请输入字典类型' },
        {
          validateTrigger: 'onBlur',
          validator: async (rule, val) => {
            if (val) {
              try {
                await checkDictType(_.assign(id ? { id } : {}, { dictType: val }));
                return Promise.resolve();
              } catch (e) {
                return Promise.reject(new Error(e?.description || '重复校验不通过'));
              }
            }
            return Promise.resolve();
          },
        },
      ],
      component: Input,
      componentProps: {
        maxLength: 24,
        allowClear: true,
        placeholder: '请输入字典类型',
        autoComplete: 'off',
      },
    },
    {
      name: 'dictStatus',
      label: '字典状态',
      initialValue: _.head(statusDict)?.value || '',
      rules: [{ required: true, message: '请选择字典状态' }],
      component: Group,
      componentProps: {},
      componentChildren: statusDict.map((item) => (
        <Radio key={item.value} value={item.value}>
          {item.label}
        </Radio>
      )),
    },
  ];

  // 字典状态
  const initDictStatusList = async () => {
    try {
      const res = await fetchAvailableDictChildList({ dictType: 'dict_status' });
      return _.isArray(res)
        ? _.filter(
            _.map(res, ({ dictValue, dictLabel }) => ({ value: dictValue, label: dictLabel })),
            ({ value }) => _.isString(value) || _.isNumber(value),
          )
        : [];
    } catch (e) {
      return [];
    }
  };
  // 初始化字典状态字典
  useEffect(() => {
    initDictStatusList().then((currentStatusDict) => {
      setInitialLoading(false);
      setStatusDict(currentStatusDict);
    });
  }, []);
  // 表单初始化
  useEffect(() => {
    if (visible) {
      if (id) {
        form.setFieldsValue(_.pick(options, _.map(formList, 'name')));
        return;
      }
    }
    form.resetFields();
  }, [visible]);

  return (
    <DraggableModal
      title={`字典${id ? '编辑' : '添加'}${dictName ? '（' + dictName + '）' : ''}`}
      visible={visible}
      onCancel={handleCancel}
      footer={[
        <DebounceButton key="cancel" disabled={actionLoading} onClick={closeModal}>
          取消
        </DebounceButton>,
        <DebounceButton
          key="confirm"
          type="primary"
          loading={actionLoading}
          onClick={handleConfirm}
        >
          提交
        </DebounceButton>,
      ]}
    >
      <Spin spinning={initialLoading} tip={'初始化..'}>
        <Form {...layout} form={form} name="dict-form">
          {formList.map(
            (item) =>
              item && (
                <Form.Item
                  key={item.name}
                  {..._.pick(item, ['name', 'label', 'rules', 'initialValue', 'validateTrigger'])}
                >
                  {item.component
                    ? React.createElement(
                        item.component,
                        { ...item.componentProps },
                        item.componentChildren,
                      )
                    : null}
                </Form.Item>
              ),
          )}
        </Form>
      </Spin>
    </DraggableModal>
  );
};
